#!/usr/bin/env python3

# wget2.py - operations for wget2
#
# Copyright (c) 2019-2023 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
from ._util import Util, LastUpdateTime
from ._main import AppStat, AppImplBase


# general timeout
# for not-continuable operation, operation itself should have separate timeout so that the connection is kept as long as possible
TIMEOUT = 10

# wait 1 seconds between retries
RETRY_WAIT = 1


SOURCE_CONTINUABLE = 1
SOURCE_NOT_CONTINUABLE = 2
SOURCE_DETECT_CONTINUABLE = 3


class AppImpl(AppImplBase):

    _BINARY_PATH = "/usr/bin/wget2"

    _ETC_CFG_PATH = "/etc/wget2rc"

    @staticmethod
    def get_name():
        return "wget2"

    def is_installed(self):
        return os.path.exists(self._BINARY_PATH)

    def system_get_info(self, app_data_dir):
        if not self.is_installed():
            return (AppStat.NOT_INSTALLED, None, None)

        appStat, msg = self._parseAndCheckWget2rc(self._BINARY_PATH)
        if appStat == AppStat.FULLY_ROBUSTIFIED:
            return (appStat, msg, LastUpdateTime.read(app_data_dir))
        elif appStat == AppStat.NOT_ROBUSTIFIED or appStat == AppStat.NOT_MANAGEABLE:
            return (appStat, msg, None)
        else:
            assert False

    def system_robustify_config(self, app_data_dir):
        self._modifyWget2rc(self._ETC_CFG_PATH)
        LastUpdateTime.write(app_data_dir)

    def user_get_info(self):
        assert False

    def user_robustify_config(self, username):
        assert False

    def _parseAndCheckWget2rc(self, filepath):
        if not os.path.exists(filepath):
            return (AppStat.NOT_ROBUSTIFIED, "")
        if not os.path.isfile(filepath):
            return (AppStat.NOT_MANAGEABLE, "%s is not a file" % (self._ETC_CFG_PATH))

        # FIXME: add check

        return (AppStat.NOT_ROBUSTIFIED, "")

    def _modifyWget2rc(self, filepath):
        # FIXME: do modify
        pass


def get_extra_cli_parameters(source_continuable=SOURCE_CONTINUABLE):
    if source_continuable == SOURCE_CONTINUABLE:
        return ["-t", "0", "-w", str(RETRY_WAIT), "--random-wait", "-T", str(TIMEOUT)]
    elif source_continuable == SOURCE_NOT_CONTINUABLE:
        # we don't modify "--read-timeout" here so that the connection is kept as long as possible
        return ["-t", "0", "-w", str(RETRY_WAIT), "--random-wait", "--dns-timeout=%d" % (TIMEOUT), "--connect-timeout=%d" % (TIMEOUT)]
    else:
        assert False
